﻿using System.Windows;
using System.Windows.Input;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Flow;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;

namespace Labthink.PCSoft.UniversalHost4.Instrument.Forms
{
    public partial class FrmTagAndRemarkDetail
    {
        public TestIndex Ti { get; set; }

        public FrmTagAndRemarkDetail()
        {
            InitializeComponent();
        }

        private void BtnSave_OnClick(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty(TxtRemark.Value) && string.IsNullOrEmpty(TxtTag.Value)) return;
            _triggerButtonsStatus(false);
            var tr = new TagAndRemark
            {
                Tag = TxtTag.Value,
                Remark = TxtRemark.Value,
                TestId = Ti.TestId
            };

            var r = HistoryRepository.UpdateTagAndRemark(tr, Common.CurrentUser.UserName);
            if (r > 0)
            {
                MyMessageBox.Show(this,LanguageManager.GetLanguageValue("ActionSuccess"));
                var msg = LanguageManager.GetLanguageValue("OP-UpdateTagOrRemark",Ti.TestId);
                LogRepository.AddLog(msg, "Data");
            }
            else
            {
                MyMessageBox.Show(this, LanguageManager.GetLanguageValue("ActionFail"));
            }
            _triggerButtonsStatus(true);
            if (r >= 0)
            {
                DialogResult = true;
                Close();
            }
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void TagAndRemark_OnLoaded(object sender, RoutedEventArgs e)
        {
            _triggerButtonsStatus(false);
            var tr = HistoryRepository.GetTagAndRemark(Ti.TestId);
            if (!string.IsNullOrEmpty(tr.Tag) || !string.IsNullOrEmpty(tr.Remark) ||
                Ti.OpName !=Common.CurrentUser.UserName)
            {
                BtnSave.Visibility = Visibility.Collapsed;
            }

            BtnSave.Visibility = Visibility.Visible;

            TxtTag.Value = tr.Tag;
            TxtRemark.Value = tr.Remark;
            _triggerButtonsStatus(true);
        }

        private void _triggerButtonsStatus(bool status)
        {
            BtnSave.IsEnabled = status;
            BtnCancel.IsDefault = status;
            if(status ) Loading.Visibility = Visibility.Collapsed;
            else Loading.Visibility = Visibility.Visible;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void FrmTagAndRemarkDetail_OnMouseMove(object sender, MouseEventArgs e)
        {
            
        }
    }
}
